package wx

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/xlstudio/wxbizdatacrypt"
	"log"
	"my-new-gin/configs"
	"net/http"
	"net/url"
)

var (
	app_id  string
	secret string
)

func init()  {
	wxConf := configs.GetWXConf()
	app_id = wxConf.AppId
	secret = wxConf.Secret
}

func WXLogin(js_code string) (map[string]interface{}, error) {

	url := "https://api.weixin.qq.com/sns/jscode2session?app_id=%s&secret=%s&js_code=%s&grant_type=authorization_code"
	resp, err := http.Get(fmt.Sprintf(url, app_id, secret, js_code))
	//关闭资源
	if resp != nil && resp.Body != nil {
		defer resp.Body.Close()
	}
	if err != nil {
		return nil, errors.New("WechatLogin request err :" + err.Error())
	}

	var jMap map[string]interface{}
	err = json.NewDecoder(resp.Body).Decode(&jMap)

	if err != nil {
		return nil, errors.New("request token response json parse err :" + err.Error())

	}
	if jMap["errcode"] == nil || jMap["errcode"] == 0 {

		return jMap, nil
	} else {
		//返回错误信息
		errcode := jMap["errcode"].(string)
		errmsg := jMap["errmsg"].(string)
		err = errors.New(errcode + ":" + errmsg)
		return nil, err
	}
}

func DecryptWXOpenData(sessionKey, encryptedData, iv string) (map[string]interface{}, error) {
	pc := wxbizdatacrypt.WxBizDataCrypt{AppID: app_id, SessionKey: sessionKey}
	result, err := pc.Decrypt(encryptedData, iv, false) //第三个参数解释： 需要返回 JSON 数据类型时 使用 true, 需要返回 map 数据类型时 使用 false
	if err != nil {
		return nil, err
	}
	return result.(map[string]interface{}),nil
}

func AesDecrypt(crypted, key, iv []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	//blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, iv)
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	//获取的数据尾端有'/x0e'占位符,去除它
	for i, ch := range origData {
		if ch == '\x0e' {
			origData[i] = ' '
		}
	}
	//{"phoneNumber":"15082726017","purePhoneNumber":"15082726017","countryCode":"86","watermark":{"timestamp":1539657521,"app_id":"wx4c6c3ed14736228c"}}//<nil>
	return origData, nil
}

func GetWXToken() (string, error) {
	u, err := url.Parse("https://api.weixin.qq.com/cgi-bin/token")
	if err != nil {
		log.Fatal(err)
	}
	paras := &url.Values{}
	//设置请求参数
	paras.Set("app_id", app_id)
	paras.Set("secret", secret)
	paras.Set("grant_type", "client_credential")
	u.RawQuery = paras.Encode()
	resp, err := http.Get(u.String())
	//关闭资源
	if resp != nil && resp.Body != nil {
		defer resp.Body.Close()
	}
	if err != nil {
		return "", errors.New("request token err :" + err.Error())
	}

	jMap := make(map[string]interface{})
	err = json.NewDecoder(resp.Body).Decode(&jMap)
	if err != nil {
		return "", errors.New("request token response json parse err :" + err.Error())
	}
	if jMap["errcode"] == nil || jMap["errcode"] == 0 {
		accessToken, _ := jMap["access_token"].(string)
		return accessToken, nil
	} else {
		//返回错误信息
		errcode := jMap["errcode"].(string)
		errmsg := jMap["errmsg"].(string)
		err = errors.New(errcode + ":" + errmsg)
		return "", err
	}

}
